<template>
    <view class="soil-monitoring-container">
        <page-header title="土壤摘情"></page-header>

        <view class="content">
            <view class="section-title">
                <text>土地摘情监测</text>
                <view class="last-time">
                    <uni-icons type="clock" size="14" color="#999"></uni-icons>
                    <text>最近监测：{{ lastMonitoringTime }}</text>
                </view>
            </view>

            <!-- 地块信息卡片 -->
            <view class="plot-card" v-for="(plot, index) in plotsData" :key="index">
                <view class="plot-header">
                    <view class="plot-title">
                        <image class="plot-icon" src="/static/images/caishou.png"></image>
                        <text>{{ plot.name }}</text>
                    </view>
                    <text :class="['status-tag', getStatusClass(plot.status)]">
                        {{ plot.status }}
                    </text>
                </view>

                <view class="depth-labels">
                    <view class="depth-label"></view>
                    <view class="depth-label">20cm</view>
                    <view class="depth-label">40cm</view>
                    <view class="depth-label">60cm</view>
                </view>

                <view class="data-section">
                    <view class="data-type">
                        <text class="data-title">温度</text>
                        <view class="depth-values">
                            <text :class="['data-value', getValueClass(plot.temperature.status20)]">
                                {{ plot.temperature.value20 }}
                            </text>
                            <text class="unit">°C</text>
                            <text :class="['data-value', getValueClass(plot.temperature.status40)]">
                                {{ plot.temperature.value40 }}
                            </text>
                            <text class="unit">°C</text>
                            <text :class="['data-value', getValueClass(plot.temperature.status60)]">
                                {{ plot.temperature.value60 }}
                            </text>
                            <text class="unit">°C</text>
                        </view>
                    </view>
                    <view class="data-type">
                        <text class="data-title">湿度</text>
                        <view class="depth-values">
                            <text :class="['data-value', getValueClass(plot.humidity.status20)]">
                                {{ plot.humidity.value20 }}
                            </text>
                            <text class="unit">%</text>
                            <text :class="['data-value', getValueClass(plot.humidity.status40)]">
                                {{ plot.humidity.value40 }}
                            </text>
                            <text class="unit">%</text>
                            <text :class="['data-value', getValueClass(plot.humidity.status60)]">
                                {{ plot.humidity.value60 }}
                            </text>
                            <text class="unit">%</text>
                        </view>
                    </view>
                </view>

                <view :class="['alert-message', getAlertClass(plot.status)]">
                    <text>{{ plot.message }}</text>
                </view>
            </view>

            <!-- 七天湿度趋势 -->
            <view class="trend-section">
                <view class="trend-title">七天湿度趋势</view>
                <humidity-trend :depthData="humidityTrendData"></humidity-trend>
            </view>
        </view>
    </view>
</template>

<script>
import uniIcons from '@/uni_modules/uni-icons/components/uni-icons/uni-icons.vue'
import PageHeader from '@/components/PageHeader/index.vue'
import HumidityTrend from '@/components/HumidityTrend/index.vue'
import { other } from '@/utils/api/index.js'
import { formatDateChinese, formatImages } from '@/utils/util.js'

export default {
    components: {
        uniIcons,
        PageHeader,
        HumidityTrend,
    },
    data() {
        return {
            lastMonitoringTime: '',
            plotsData: [],
            // 湿度趋势数据
            humidityTrendData: {
                dates: [],
                depth20: [],
                depth40: [],
                depth60: [],
            },
            loading: false,
            pageParams: {
                pageNo: 1,
                pageSize: 99,
            },
        }
    },
    onShow() {
        this.fetchData()
        this.getSoilMoistureLineChart()
    },
    methods: {
        async fetchData() {
            this.loading = true
            uni.showLoading({ title: '加载中...' })

            try {
                // 计算最近7天的日期范围
                const endDate = new Date()
                const startDate = new Date()
                startDate.setDate(startDate.getDate() - 6) // 获取7天前的日期

                // 格式化日期为 YYYY-MM-DD HH:mm:ss
                const formatDate = (date) => {
                    const year = date.getFullYear()
                    const month = String(date.getMonth() + 1).padStart(2, '0')
                    const day = String(date.getDate()).padStart(2, '0')
                    return `${year}-${month}-${day} 00:00:00`
                }

                const params = {
                    startDate: formatDate(startDate),
                    endDate: formatDate(endDate),
                }
                const res = await other.getSoilMoisturePage(params)

                if (res.code === 0 && res.data) {
                    // 处理数据
                    this.processData(res.data)
                } else {
                    uni.showToast({
                        title: '获取数据失败',
                        icon: 'none',
                    })
                }
            } catch (error) {
                console.error('获取土壤墒情数据失败', error)
                uni.showToast({
                    title: '获取数据失败',
                    icon: 'none',
                })
            } finally {
                this.loading = false
                uni.hideLoading()
            }
        },
        // 土壤墒情折线图
        async getSoilMoistureLineChart() {
            // 计算最近7天的日期范围
            const endDate = new Date()
            const startDate = new Date()
            startDate.setDate(startDate.getDate() - 6) // 获取7天前的日期

            // 格式化日期为 YYYY-MM-DD HH:mm:ss
            const formatDate = (date) => {
                const year = date.getFullYear()
                const month = String(date.getMonth() + 1).padStart(2, '0')
                const day = String(date.getDate()).padStart(2, '0')
                return `${year}-${month}-${day} 00:00:00`
            }

            const params = {
                startDate: formatDate(startDate),
                endDate: formatDate(endDate),
            }

            try {
                const res = await other.getSoilMoistureLineChart(params)
                if (res.code === 0 && res.data) {
                    // 处理日期格式，将 "2025-07-30T00:00" 转换为 "7/30"
                    const formattedDates = res.data.dates.map((dateStr) => {
                        const date = new Date(dateStr)
                        return `${date.getMonth() + 1}/${date.getDate()}`
                    })

                    // 更新图表数据
                    this.humidityTrendData = {
                        dates: formattedDates,
                        depth20: res.data.depth20.map(Number), // 转换为数字
                        depth40: res.data.depth40.map(Number),
                        depth60: res.data.depth60.map(Number),
                    }
                } else {
                    uni.showToast({
                        title: '获取图表数据失败',
                        icon: 'none',
                    })
                }
            } catch (error) {
                console.error('获取土壤墒情折线图数据失败', error)
                uni.showToast({
                    title: '获取图表数据失败',
                    icon: 'none',
                })
            }
        },

        processData(dataList) {
            if (!dataList || dataList.length === 0) return

            // 更新最近监测时间
            if (dataList[0].createTime) {
                const date = new Date(dataList[0].createTime[0] || dataList[0].createTime)
                this.lastMonitoringTime = formatDateChinese(date)
            }

            // 处理地块数据
            const plotsData = dataList.map((item) => {
                // 根据grade确定状态：0-正常，1-注意，2-严重
                let status = '正常'
                let statusCode = 'normal'
                let message = '当前情况良好，无需处理'

                if (item.grade === '1') {
                    status = '注意'
                    statusCode = 'warning'
                    message = '土壤状态需要注意，请及时检查'
                } else if (item.grade === '2') {
                    status = '严重'
                    statusCode = 'danger'
                    message = '土壤状态异常，请立即处理'
                }

                return {
                    name: item.plotName || `地块${item.plotId || ''}`,
                    status: status,
                    temperature: {
                        value20: item.temperature20 || '--',
                        status20: this.getStatusByValue(item.temperature20, 'temperature'),
                        value40: item.temperature40 || '--',
                        status40: this.getStatusByValue(item.temperature40, 'temperature'),
                        value60: item.temperature60 || '--',
                        status60: this.getStatusByValue(item.temperature60, 'temperature'),
                    },
                    humidity: {
                        value20: item.humidity20 || '--',
                        status20: this.getStatusByValue(item.humidity20, 'humidity'),
                        value40: item.humidity40 || '--',
                        status40: this.getStatusByValue(item.humidity40, 'humidity'),
                        value60: item.humidity60 || '--',
                        status60: this.getStatusByValue(item.humidity60, 'humidity'),
                    },
                    message: message,
                }
            })

            this.plotsData = plotsData

            // 使用静态数据作为湿度趋势
            this.humidityTrendData = {
                dates: ['6/14', '6/15', '6/16', '6/17', '6/18'],
                depth20: [45, 38, 50, 68, 55],
                depth40: [35, 30, 45, 55, 45],
                depth60: [30, 15, 20, 35, 25],
            }
        },

        // 根据值判断状态
        getStatusByValue(value, type) {
            if (!value) return 'normal'
            value = Number(value)

            if (type === 'temperature') {
                // 温度状态判断标准
                if (value > 30) return 'danger'
                if (value > 25) return 'warning'
                return 'normal'
            } else if (type === 'humidity') {
                // 湿度状态判断标准
                if (value < 20) return 'danger'
                if (value < 30) return 'warning'
                return 'normal'
            }

            return 'normal'
        },

        // 工具函数
        getStatusClass(status) {
            switch (status) {
                case '正常':
                    return 'status-normal'
                case '注意':
                    return 'status-warning'
                case '严重':
                    return 'status-danger'
                default:
                    return ''
            }
        },
        getValueClass(status) {
            switch (status) {
                case 'normal':
                    return 'value-normal'
                case 'warning':
                    return 'value-warning'
                case 'danger':
                    return 'value-danger'
                default:
                    return ''
            }
        },
        getAlertClass(status) {
            switch (status) {
                case '正常':
                    return 'alert-normal'
                case '注意':
                    return 'alert-warning'
                case '严重':
                    return 'alert-danger'
                default:
                    return ''
            }
        },
    },
}
</script>

<style lang="scss">
.soil-monitoring-container {
    min-height: 100vh;
    background-color: #f5f5f5;
    display: flex;
    flex-direction: column;

    .content {
        flex: 1;
        padding: 20rpx;

        .section-title {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20rpx 10rpx;
            font-size: 32rpx;
            font-weight: bold;

            .last-time {
                font-size: 24rpx;
                color: #999;
                display: flex;
                align-items: center;

                .icon-time {
                    margin-right: 5rpx;
                }
            }
        }

        .plot-card {
            background-color: #fff;
            border-radius: 16rpx;
            padding: 30rpx;
            margin-bottom: 20rpx;
            box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

            .plot-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 20rpx;

                .plot-title {
                    display: flex;
                    align-items: center;
                    font-size: 30rpx;
                    font-weight: bold;

                    .plot-icon {
                        margin-right: 10rpx;
                        width: 40rpx;
                        height: 40rpx;
                        border-radius: 8rpx;
                        background-color: #e6f0ff;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                    }
                }

                .status-tag {
                    padding: 4rpx 20rpx;
                    border-radius: 30rpx;
                    font-size: 24rpx;

                    &.status-normal {
                        background-color: #e8f5e9;
                        color: #4caf50;
                    }

                    &.status-warning {
                        background-color: #fff8e1;
                        color: #ff9800;
                    }

                    &.status-danger {
                        background-color: #ffebee;
                        color: #f44336;
                    }
                }
            }

            .depth-labels {
                display: flex;
                margin-bottom: 10rpx;

                .depth-label {
                    flex: 1;
                    text-align: center;
                    font-size: 26rpx;
                    color: #999;

                    &:first-child {
                        flex: 0.5;
                    }
                }
            }

            .data-section {
                margin-bottom: 20rpx;

                .data-type {
                    display: flex;
                    align-items: center;
                    margin-bottom: 15rpx;

                    .data-title {
                        flex: 0.5;
                        font-size: 28rpx;
                        color: #999;
                    }

                    .depth-values {
                        flex: 3;
                        display: flex;
                        justify-content: space-around;

                        .data-value {
                            font-size: 32rpx;
                            font-weight: bold;
                            text-align: center;
                            flex: 1;

                            &.value-normal {
                                color: #4caf50;
                            }

                            &.value-warning {
                                color: #ff9800;
                            }

                            &.value-danger {
                                color: #f44336;
                            }
                        }

                        .unit {
                            font-size: 24rpx;
                            color: #999;
                            margin-right: 15rpx;
                        }
                    }
                }
            }

            .alert-message {
                padding: 20rpx;
                border-radius: 8rpx;
                font-size: 26rpx;

                &.alert-normal {
                    background-color: #e8f5e9;
                    color: #4caf50;
                }

                &.alert-warning {
                    background-color: #fff8e1;
                    color: #ff9800;
                }

                &.alert-danger {
                    background-color: #ffebee;
                    color: #f44336;
                }
            }
        }

        .trend-section {
            background-color: #fff;
            border-radius: 16rpx;
            padding: 30rpx;
            margin-top: 20rpx;

            .trend-title {
                font-size: 32rpx;
                font-weight: bold;
                margin-bottom: 20rpx;
            }
        }
    }
}
</style>
